import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getCartList,
  addToCart,
  updateCartItem,
  removeFromCart,
  selectCartItem,
  clearCart,
  getCartItemCount
} from '../api/divide/cart/sdk.gen';
import type {
  AddCartRequest,
  UpdateCartRequest,
} from '../api/divide/cart/types.gen';
import { useCartStore } from '../store/cartStore';
import { message } from 'antd';

// 选择购物车商品的请求参数
interface SelectCartRequest {
  courseId: number;
  selected: boolean;
}

// 购物车相关Hook
export const useCart = () => {
  const queryClient = useQueryClient();
  const {
    setCartItems,
    setCartItemCount,
    setSelectedItems,
    calculateSelectedTotal,
    clearLocalCart
  } = useCartStore();

  // 获取购物车列表
  const {
    data: cartList,
    isLoading: isLoadingCart,
    error: cartError
  } = useQuery({
    queryKey: ['cart', 'list'],
    queryFn: () => getCartList().then(res => res.data?.data || []),
    staleTime: 1000 * 60, // 1分钟缓存
  });

  // 使用 useEffect 处理数据变化
  React.useEffect(() => {
    if (cartList) {
      setCartItems(cartList);
      // 计算选中的商品
      const selected = cartList.filter((item) => item.selected);
      setSelectedItems(selected);
      calculateSelectedTotal();
    }
  }, [cartList, setCartItems, setSelectedItems, calculateSelectedTotal]);

  // 获取购物车商品数量
  const {
    data: cartCount = 0
  } = useQuery({
    queryKey: ['cart', 'count'],
    queryFn: () => getCartItemCount().then(res => res.data?.data || 0),
    staleTime: 1000 * 60
  });

  // 使用 useEffect 处理购物车数量变化
  React.useEffect(() => {
    setCartItemCount(cartCount);
  }, [cartCount, setCartItemCount]);

  // 添加到购物车
  const addToCartMutation = useMutation({
    mutationFn: (params: AddCartRequest) => addToCart({ body: params }),
    onSuccess: () => {
      message.success('添加成功');
      // 刷新购物车数据
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
    onError: (error) => {
      message.error('添加失败：' + (error as Error).message);
    }
  });

  // 更新购物车商品
  const updateCartMutation = useMutation({
    mutationFn: (params: UpdateCartRequest) => updateCartItem({ body: params }),
    onSuccess: () => {
      message.success('更新成功');
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
    onError: (error) => {
      message.error('更新失败：' + (error as Error).message);
    }
  });

  // 从购物车删除
  const removeFromCartMutation = useMutation({
    mutationFn: (courseId: number) => removeFromCart({ path: { courseId } }),
    onSuccess: () => {
      message.success('删除成功');
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
    onError: (error) => {
      message.error('删除失败：' + (error as Error).message);
    }
  });

  // 选择/取消选择商品
  const selectCartItemMutation = useMutation({
    mutationFn: ({ courseId, selected }: SelectCartRequest) => 
      selectCartItem({ 
        path: { cartItemId: courseId }, 
        query: { selected } 
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
    onError: (error) => {
      message.error('操作失败：' + (error as Error).message);
    }
  });

  // 清空购物车
  const clearCartMutation = useMutation({
    mutationFn: () => clearCart({}),
    onSuccess: () => {
      message.success('购物车已清空');
      queryClient.invalidateQueries({ queryKey: ['cart'] });
      clearLocalCart();
    },
    onError: (error) => {
      message.error('清空失败：' + (error as Error).message);
    }
  });

  return {
    // 数据
    cartList: cartList || [],
    cartCount: cartCount || 0,
    isLoadingCart,
    cartError,

    // 操作函数
    addToCart: addToCartMutation.mutate,
    updateCartItem: updateCartMutation.mutate,
    removeFromCart: removeFromCartMutation.mutate,
    selectCartItem: selectCartItemMutation.mutate,
    clearCart: clearCartMutation.mutate,

    // 状态
    isAdding: addToCartMutation.isPending,
    isUpdating: updateCartMutation.isPending,
    isRemoving: removeFromCartMutation.isPending,
    isSelecting: selectCartItemMutation.isPending,
    isClearing: clearCartMutation.isPending
  };
};